﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using PaulBeck.Timesheet.BOL;

namespace PaulBeck.Timesheet.WebParts.Consultant
{
    public partial class ConsultantUserControl : UserControl
    {

        #region "Properties"

        public int UserId
        {
            get
            {
                object o = ViewState["UserId"];
                return (o == null) ? 0 : (int)o;
            }
            set
            {
                ViewState["UserId"] = value;
            }
        }

        #endregion

        #region "Control Events"

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    string friendlyName = CommonWFE.CurrentUserName();
                    string loginName = CommonWFE.CurrentUserLoginName();
                    // Display the current consultant/resource/user
                    UserId = ConsultantBOL.GetConsultantIdByLoginKey(loginName);
                    if (UserId > 0) { ddlConsultant.Items.Add(new ListItem(friendlyName, UserId.ToString())); }
                    if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                    {
                        // Get all resources to allow the admin to select other consultants to modify
                        foreach (var item in ConsultantBOL.GetAllConsultants())
                        {
                            ddlConsultant.Items.Add(new ListItem(item.Name, item.ResourceId.ToString()));
                        }
                    }
                    else
                    {
                        ddlConsultant.Enabled = false;
                    }

                }
                catch (InvalidOperationException ex)
                {
                    // TODO! Log error
                }
            }
        }



        protected void ddlConsultant_SelectedIndexChanged(object sender, EventArgs e)
        {
            UserId = Convert.ToInt32(ddlConsultant.SelectedValue);
        }

        #endregion

        public int GetResourceId()
        {
            return UserId;
        }


    }
}
